package com.chen.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class CallableTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        MyThread myThread = new MyThread();
        FutureTask<Integer> futureTask = new FutureTask<>(myThread);

        new Thread(futureTask, "A").start();
        // 只会打印一个call执行了，因为结果被缓存了，效率高
        new Thread(futureTask, "B").start();
        // 获得返回值需要时间，get方法可能阻塞，建议放到语句最后或者使用异步通信
        Integer value = futureTask.get();
        System.out.println(value);

    }
}

class MyThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println("Call方法执行了");
        // 返回值可能要花费很多时间
        return 1024;
    }
}
